package com.sptpc.library.controller;

import cn.hutool.json.JSONObject;
import com.sptpc.library.model.Book;
import com.sptpc.library.model.Borrowing;
import com.sptpc.library.model.vo.UserVo;
import com.sptpc.library.service.BookService;
import com.sptpc.library.model.User;
import com.sptpc.library.service.BorrowingService;
import com.sptpc.library.service.UserService;
import com.sptpc.library.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private BorrowingService borrowingService;
    @Autowired
    private BookService bookService;

    // 增
    @PostMapping(value = "/insert", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseBody
    public ServerResponse insert(@RequestParam(name = "userName") String userName,
                                 @RequestParam(name = "userPassword") String userPassword,
                                 @RequestParam(name = "userTrueName") String userTrueName,
                                 @RequestParam(name = "sex") String sex,
                                 @RequestParam(name = "userType")Long userType) {
        return ServerResponse.createBySuccess(userService.insert(userName,userPassword,userTrueName,sex,userType));
    }

    // 删
    // 根据userTrueName
    @PostMapping(value = "/delete",params = "userTrueName")
    @ResponseBody
    public ServerResponse deleteByTrueName(@RequestParam(name = "userTrueName") String userTrueName) {
        return ServerResponse.createBySuccess(userService.deleteByTrueName(userTrueName));
    }

    // 查
    // 查询所有
    @GetMapping("/")
    @ResponseBody
    public ServerResponse list() {
        return  ServerResponse.createBySuccess(userService.findAll());
    }

    // 根据userId查询
    @PostMapping(value = "/find",params = "userId")
    @ResponseBody
    public ServerResponse findByUserId(@RequestParam Long userId) {
        return ServerResponse.createBySuccess(userService.findByUserId(userId));
    }
    // 根据userName查询
    @PostMapping(value = "/find",params = "userName")
    @ResponseBody
    public ServerResponse findByName(@RequestParam String userName){
        return ServerResponse.createBySuccess(userService.findAllByName(userName));
    }
    // 根据userTrueName查询
    @PostMapping(value = "/find", params = "userTrueName")
    @ResponseBody
    public ServerResponse findByTrueName(@RequestParam String userTrueName) {
        return ServerResponse.createBySuccess(userService.findAllByTrueName(userTrueName));
    }
    // 模糊查询 userTrueName
    @PostMapping(value = "/findOneLike",params = "userTrueName")
    @ResponseBody
    public User findOneLike(@RequestParam(name = "userTrueName") String userTrueName) {
        return userService.findOneLike(userTrueName);
    }

    // 改
    @PostMapping(value = "/update", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseBody
    public ServerResponse update(UserVo userVo) {
        return ServerResponse.createBySuccess(userService.update(userVo));
    }

    // 新增
    @PostMapping(value = "add" ,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseBody
    public ServerResponse add(UserVo userVo) {
        return ServerResponse.createBySuccess(userService.save(userVo));
    }

    // 查询
//    @PostMapping(value = "/find", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
//    @ResponseBody
//    public ServerResponse find()

    // 删除
    @GetMapping(value = "delete",params = "userId")
    @ResponseBody
    public ServerResponse delete(@RequestParam Integer userId) {
        User user = userService.findByUserId(userId.longValue());
        if (user != null) {
            if (userService.deleteByUserId(userId.longValue()) != null) {
                return ServerResponse.createBySuccessMessage("删除成功");
            } else {
                return ServerResponse.createByErrorMessage("删除不成功");
            }
        } else {
            return ServerResponse.createByErrorMessage("删除失败");
        }
    }

    // 视图
    // 用户管理
    @GetMapping("/user_view")
    @ResponseBody
    public ModelAndView user_view () {
        ModelAndView mv = new ModelAndView("admin/admin_user");
        List<User> userList = userService.findAll();
        mv.addObject("userList",userList);
        return mv;
    }

    // 用户新增
    @GetMapping("/user_add")
    @ResponseBody
    public ModelAndView user_add () {
        ModelAndView mv = new ModelAndView("admin/user_add");
        List<User> userList = userService.findAll();
        mv.addObject("userList",userList);
        return mv;
    }

    // 管理员用户查询
//    @GetMapping(value = "/user_select")
//    @ResponseBody
//    public ModelAndView user_select (UserVo userVo) {
//        ModelAndView mv = new ModelAndView("admin/admin_user");
//        List<User> userList = userService.select(userVo);
//        mv.addObject("userList",userList);
//        return mv;
//    }

    // 用户编辑
    @GetMapping(value = "/user_edit",params = "userId")
    @ResponseBody
    public ModelAndView user_edit (@RequestParam Long userId) {
        ModelAndView mv = new ModelAndView("admin/user_edit");
        User user = userService.findByUserId(userId);
        mv.addObject("user",user);
        return mv;
    }

    // 用户编辑信息然后进行保存
    @PostMapping(value = "/updatePersonal",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public JSONObject updatePersonal(@RequestBody UserVo userVo, HttpSession httpSession) {
        JSONObject resObj = new JSONObject();
        User newUserName = userService.findOneByUserName(userVo.getUserName());
        String oldUserName = userService.findByUserId(userVo.getUserId()).getUserName();
        if(newUserName == null || userVo.getUserName().equals(oldUserName)){
            User user = userService.updatePersonal(userVo);
            httpSession.setAttribute("user", user);
            resObj.put("code", 0);
            resObj.put("msg", "修改成功");
            return resObj;
        }else {
            resObj.put("code", 1);
            resObj.put("msg", "修改失败,用户名已存在，请修改为其他用户名");
            return resObj;
        }
    }

    @GetMapping("/updatePassword")
    @ResponseBody
    public ModelAndView updatePassword () {
        ModelAndView mv = new ModelAndView("user/password");
        return mv;
    }

    @PostMapping(value = "/updatePassword", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public JSONObject updatePassword(@RequestBody UserVo userVo) {
        JSONObject resObj = new JSONObject();
        User user = userService.findByUserId(userVo.getUserId());
        if (user != null) {
            if(user.getUserPassword().equals(userVo.getOldPassword())){
                user.setUserPassword(userVo.getUserPassword());
                userService.update(user);
                resObj.put("code", 0);
                resObj.put("msg", "密码修改成功");
                return resObj;
            }else{
                resObj.put("code",1);
                resObj.put("msg", "原密码错误，修改失败");
                return resObj;
            }
        }
        resObj.put("code", 1);
        resObj.put("msg", "修改错误");
        return resObj;
    }
    // 用户 借阅记录
    @GetMapping("/user_borrowing_view")
    @ResponseBody
    public ModelAndView user_lend_view (HttpSession httpSession) {
        ModelAndView mv = new ModelAndView("/user/borrowing");
        User user = (User)httpSession.getAttribute("user");
        mv.addObject("borrowingList",borrowingService.findByUserId(user.getUserId()));
        return mv;
    }
    // 用户 图书查询
    @GetMapping(value = "/user_book_view")
    @ResponseBody
    public ModelAndView book_view () {
        ModelAndView mv = new ModelAndView("user/book");
        List<Book> bookList = bookService.findAll();
        mv.addObject("bookList",bookList);
        return mv;
    }
    // 用户 个人信息
    @GetMapping("/user_personal_view")
    @ResponseBody
    public ModelAndView user_personal_view () {
        ModelAndView mv = new ModelAndView("user/personal");
        return mv;
    }

    // 管理员 用户查询
    // 弹窗
    @GetMapping("/user_select_w")
    @ResponseBody
    public ModelAndView user_select_w () {
        ModelAndView mv = new ModelAndView("admin/user_select_w");
        return mv;
    }
    // 查询页面
    @GetMapping("/admin_select")
    @ResponseBody
    public ModelAndView admin_select(UserVo userVo) {
        ModelAndView mv = new ModelAndView("admin/admin_user");
        List<User> userList = userService.findAllByUserNameOrUserTrueName(userVo.getUserName(),userVo.getUserTrueName());
        mv.addObject("userList",userList);
        return mv;
    }

    // 查询页面
    @GetMapping("/user_admin_select")
    @ResponseBody
    public ModelAndView user_admin_select(UserVo userVo) {
        ModelAndView mv = new ModelAndView("admin/admin_borrowing");
        List<Borrowing> borrowingList = borrowingService.findAllByUserName(userVo.getUserName());
//        List<User> userList = userService.findAllByUserNameOrUserTrueName(userVo.getUserName(),userVo.getUserTrueName());
        mv.addObject("borrowingList",borrowingList);
        return mv;
    }















}